package org.bhf.service.view;

/**
 * Copyright (c) 2007, Blue Hole Software. All rights reserved.
 * Code licensed under the Apache 2.0 License:
 * http://www.apache.org/licenses/
 */

import org.bhf.service.Constants;
import org.bhf.service.ProcessView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * The view is the <code>toString()</code> of the given. This is the default
 * if the method (service method, exception handler, ...) returns an object which not an instance of
 * <code>ProcessView</code>.
 */
public class LiteralProcessView implements ProcessView
{
    private final Object result;

    /**
     * Render the given object using <code>toString()</code>.
     * @param service Service object
     * @param method The target service method
     * @param result The result object to be rendered literally. May be <code>null</code>, in
     *  which case nothing is rendered.
     */
    public LiteralProcessView(  final Object service, final Method method, final Object result )
    {
        this.result = result;
    }

    /**
     * ProcessView contract.
     *
     * @param request Servlet request.
     * @param response Serlvet reponse.
     * @throws java.io.IOException ConversionError during JSON rendering
     * @exclude
     */
    public void processView( final HttpServletRequest request, final HttpServletResponse response, final ServletContext servletContext )
        throws IOException
    {
        if( result != null && result != Constants.VOID )
        {
            final String message = result.toString();

            response.setContentType( "text/plain" );
            response.setContentLength( message.length() );

            final PrintWriter out = response.getWriter();

            out.print( message );
            out.close();
        }
    }
}